import requests
import time
import math

from PIL.ImageChops import offset


def get_place_name(location, key):
    url = "https://restapi.amap.com/v3/geocode/regeo"
    params = {"location": location, "key": key, "extensions": "base"}
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        if data.get("status") == "1":
            return data.get("regeocode", {}).get("formatted_address", "未知地点")
    except Exception as err:
        print(f"获取地名时出错: {err}")
    return "未知地点"

def search_nearby_places(origin, keywords, key, offset):
    url = "https://restapi.amap.com/v3/place/around"
    params = {"key": key, "location": origin, "keywords": keywords, "offset": offset}
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        pois = data.get("pois", [])
        if pois:
            print(f"已为您检索到{len(pois)}条信息，分别为：")
            for idx, poi in enumerate(pois, 1):
                print(f"{idx}. {poi.get('name')}")
            choice = int(input("请选择目的地编号: "))
            return pois[choice - 1].get("location")
    except Exception as err:
        print(f"搜索附近地点时出错: {err}")
    return None

def plan_route(origin, destination, key):
    url = "https://restapi.amap.com/v3/direction/walking"
    params = {"origin": origin, "destination": destination, "key": key}
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        steps = data.get("route", {}).get("paths", [])[0].get("steps", [])
        return steps
    except Exception as err:
        print(f"路径规划时出错: {err}")
    return []

def haversine(lon1, lat1, lon2, lat2):
    lon1, lat1, lon2, lat2 = map(math.radians, [float(lon1), float(lat1), float(lon2), float(lat2)])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    return 6371 * c * 1000  # 返回距离（米）

def navigate(current_location, destination, key):
    steps = plan_route(current_location, destination, key)
    if steps:
        print(f"导航指令: {steps[0].get('instruction')}")
    else:
        print("无法获取路径信息。")

def simulate_movement(current_location, destination_location):
    current_location[0] += (destination_location[0] - current_location[0]) * 0.5
    current_location[1] += (destination_location[1] - current_location[1]) * 0.5
    return current_location

def main():
    origin = "113.375059,23.054668"          # 初始位置（由GPS获取）
    key = "251d8e52937324e031c722f506a9cc9e" # 高德API KEY
    offset = 5 # 每页记录数据

    origin_name = get_place_name(origin, key)
    print(f"当前位置为: {origin_name}")

    keywords = input("请输入目的地: ")

    destination = search_nearby_places(origin, keywords, key, offset)
    if destination:
        print(f"正在为您导航前往 {get_place_name(destination, key)}")
        current_location = list(map(float, origin.split(',')))
        destination_location = list(map(float, destination.split(',')))

        while True:
            navigate(f"{current_location[0]},{current_location[1]}", destination, key)
            distance = haversine(*current_location, *destination_location)
            if distance < 10:
                print("您已到达目的地。")
                break
            current_location = simulate_movement(current_location, destination_location)
            time.sleep(2)
    else:
        print("未选择有效的目的地。")

if __name__ == "__main__":
    main()